//
//  MyCouponViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MyCouponViewController.h"
#import "MyCouponTableViewCell.h"
#import "UselessCouponViewController.h"
@interface MyCouponViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIImageView *_imageView;
    UILabel *_tipLbl;
}
@property (nonatomic,strong)UITextField * couponInput;
@property (nonatomic,strong)UIButton    * exchangeBtn;
@property (nonatomic,strong)UIButton    * cantuseBtn;
@property (nonatomic,strong)UITableView * mainTableView;
@property (nonatomic,strong)NSMutableArray * dataSource;
@property (nonatomic,assign)NSInteger   reFreshindex;
@end

@implementation MyCouponViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.title=@"优惠券";
    _dataSource = [NSMutableArray array];
    [self.view addSubview:self.couponInput];
    [self.view addSubview:self.exchangeBtn];
    [self.view addSubview:self.cantuseBtn];
     [self.view addSubview:self.mainTableView];
    [self.mainTableView.mj_header beginRefreshing];
    [self setUpBgView];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GeneralTool hideTabBar];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [GeneralTool showTabBar];
}
#pragma mark--刷新数据
-(void)refreshTheTableView
{
    _reFreshindex = 1;
    [_dataSource removeAllObjects];
    [_mainTableView reloadData];
    [self requestTheData];
}
-(void)addTheMoreData
{
    _reFreshindex++;
    [self requestTheData];
}
#pragma mark--请求数据
-(void)requestTheData
{
    NSString *timestamp=[GeneralTool gettimestamp];
    
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,@"IsCanUse":@"1",@"PageIndex":[NSString stringWithFormat:@"%zd",_reFreshindex],@"PageSize":@"10",@"Timestamp":timestamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"User/MyCoupon/%@/%@/%@/%@/%@/%@",GETUSERCODE,@"1",[NSString stringWithFormat:@"%zd",_reFreshindex],@"10",timestamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responses[@"IsSuccess"]intValue]==1) {
            NSArray * dataArr = [responses objectForKey:@"ReturnObject"];
            if(dataArr.count==0)
            {
                //显示没有优惠卷
                _exchangeBtn.hidden=YES;
                _cantuseBtn.hidden=YES;
                _couponInput.hidden=YES;
                _mainTableView.hidden=YES;
                _imageView.hidden=NO;
                _tipLbl.hidden=NO;
                
                return;
            }
            for (NSDictionary * couponDic in dataArr)
            {
                MyCouponModel * model = [[MyCouponModel alloc]init];
                [model setValuesForKeysWithDictionary:couponDic];
                     [_dataSource addObject:model];
            }
                if (dataArr.count<15)
                {
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }else
                {
                    [_mainTableView.mj_footer endRefreshing];
                }
        }else
        {
            [MBProgressHUD showError:@"获取信息失败"];
        }
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            if(_dataSource.count==0)
            {
                //显示没有优惠卷
                _mainTableView.hidden=YES;
                _imageView.hidden=NO;
                _tipLbl.hidden=NO;
                
            }
    }];
    
}
#pragma mark--优惠券兑换
-(UITextField *)couponInput
{
    if (!_couponInput)
    {
        _couponInput = [[UITextField alloc]initWithFrame:CGRectMake(10, 10+64, kWidth-118, 44)];
        _couponInput.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
        _couponInput.borderStyle = UITextBorderStyleRoundedRect;
        _couponInput.backgroundColor = [UIColor whiteColor];
        _couponInput.placeholder = @"请输入优惠劵码";
    }
    return _couponInput;
}
-(UIButton *)exchangeBtn
{
    if (!_exchangeBtn)
    {
        _exchangeBtn = [[UIButton alloc]initWithFrame:CGRectMake(kWidth - 98, 10+64, 88, 44)];
        _exchangeBtn.layer.cornerRadius = 5;
        _exchangeBtn.layer.borderWidth = 1;
        _exchangeBtn.layer.borderColor = [BLUECOLOR CGColor];
        [_exchangeBtn setTitle:@"兑换" forState:UIControlStateNormal];
        _exchangeBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin;
        [_exchangeBtn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
        [_exchangeBtn addTarget:self action:@selector(changeCoupon) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exchangeBtn;
}
//兑换
-(void)changeCoupon
{
    if (self.couponInput.text.length==0)
    {
        [MBProgressHUD showError:@"请输入优惠券码"];
        return;
    }
    //http://192.168.1.107:3722/User/BindCoupon
    //m_BindCouponPara(UserCode,CouponCode,Timestamp,Sign)
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"CouponCode":self.couponInput.text,
                        @"Timestamp":timeStamp,
                        };
    NSString *sign=[GeneralTool GetSin:dic];
    NSDictionary *dataDic=@{@"UserCode":GETUSERCODE,
                            @"CouponCode":self.couponInput.text,
                            @"Timestamp":timeStamp,
                            @"Sign":sign};
    NSDictionary *requestDic=@{@"m_BindCouponPara":dataDic};
    [RequestTool requestDataWithType:@"post" andUrlString:@"User/BindCoupon" andParameters:requestDic andRequestFinished:^(id responses, NSError *error)
    {
        NSLog(@"%@",responses);
        if (error) {
            [MBProgressHUD showError:@"请求失败，请稍后再试"];
        }
        if ([responses[@"IsSuccess"]intValue]==1) {
            [_mainTableView.mj_header beginRefreshing];
        }else
        {
            [MBProgressHUD showError:responses[@"ReturnString"]];
        }
    }];
}
#pragma mark--不可用优惠券
-(UIButton *)cantuseBtn
{
    if (!_cantuseBtn)
    {
        _cantuseBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, kHeight-44, kWidth, 44)];
        _cantuseBtn.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
        [_cantuseBtn setTitle:@"不可用优惠卷>>" forState:UIControlStateNormal];
        [_cantuseBtn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
        [_cantuseBtn addTarget:self action:@selector(goToUselessCoupon) forControlEvents:UIControlEventTouchUpInside];
        _cantuseBtn.backgroundColor = [UIColor clearColor];
    }
    return _cantuseBtn;
}
-(void)goToUselessCoupon
{

    UselessCouponViewController *uselessCoupon=[[UselessCouponViewController alloc]init];
    uselessCoupon.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:uselessCoupon animated:YES];
}
#pragma mark--创建没有拼单活动
-(void)setUpBgView
{
    _imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"no_coupon"]];
    _imageView.center=self.view.center;
    _imageView.hidden=YES;
    _imageView.bounds=CGRectMake(0, 5, 80, 80);
    [self.view addSubview:_imageView];
    
    _tipLbl=[[UILabel alloc]init];
    _tipLbl.center=CGPointMake(_imageView.center.x+40, _imageView.center.y+40+30);
    _tipLbl.bounds=CGRectMake(0, 0, 250, 30);
    _tipLbl.text=@"您还没有可用优惠券～";
    _tipLbl.textColor=GRAYCOLOR;
    _tipLbl.hidden=YES;
    [self.view addSubview:_tipLbl];
}

#pragma mark--表创建
-(UITableView *)mainTableView
{
    if (!_mainTableView)
    {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_exchangeBtn.frame)+10,kWidth, kHeight-CGRectGetMaxY(_exchangeBtn.frame)-10-44) style:UITableViewStylePlain];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
        _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addTheMoreData)];
        [_mainTableView registerClass:[MyCouponTableViewCell class] forCellReuseIdentifier:@"cell"];
        _mainTableView.backgroundColor = LIGHTGRAY;
        _mainTableView.tableFooterView = [UIView new];//设置当数据不多的时候，下面无cell
        _mainTableView.rowHeight=120;
        _mainTableView.sectionHeaderHeight = 0;
        _mainTableView.sectionFooterHeight = 0;
        _mainTableView.rowHeight=120;
    }
    return _mainTableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCouponTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.row > _dataSource.count-1)
    {
        return nil;
    }
    MyCouponModel * model = _dataSource[indexPath.row];
    cell.categoryNameLabel.text = model.CategoryName;//类别
    cell.categoryNamesLabel.text = model.CategoryNames;//分类
    cell.cityNamesLabel.text = model.CityNames;//城市
    cell.couponNameLabel.text = model.CouponName;
    cell.showDateLabel.text = [NSString stringWithFormat:@"有效期：%@",model.ShowDate];
    cell.showMoneyLabel.text =[NSString stringWithFormat:@"%@",model.ShowMoney] ;
    cell.showSuffixLabel.text = model.ShowSuffix;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!_isUse) {
        return;
    }
    MyCouponModel *model=_dataSource[indexPath.row];
    self.passCouponBlock(model);
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
